/**
 * 表格控件
 */
var IBizDataGrid4 = IBizControl.extend({
	construct: function(config) {
		var me = this;
		arguments.callee.$.construct.call(this,config);
		me.grid = $('#'+config.id);
		me.changeRows = [];
		me.selectRowIndx = [];
		me.tableselection = null;
		me.tableselections = {};
		//默认不加载数据
		me.defaultLoad = false; 
		if(config.defaultLoad != undefined && config.loadDefault == false){
			me.defaultLoad = config.loadDefault; 
		}
		var dataModel = {
			location: "remote",
			sorting: "remote",
			firstLoad: me.defaultLoad,
			method: "POST",
			dataType: "JSON",
			getUrl:function(){//获取请求参数
				if(me.getEditState()) {
					me.grid.pqGrid("option","pageModel.rPP",me.rPP);
				}
            	var param ={srfaction:'fetch',srfrender:'PQGRID'};
            	//设置搜索参数
            	me.fireEvent(IBizDataGrid.BEFORELOAD,me,param);
            	if(config.srfaction){
            		param.srfaction = config.srfaction;
            	}
            	if(me.grid){
            		//设置分页参数
            		var pageModel=me.grid.pqGrid( "option", "pageModel" );
            		if(pageModel){
            			var curPage=pageModel.curPage;
            			var rPP = pageModel.rPP;
            			var totalRecords = pageModel.totalRecords;
            			if(curPage && rPP){
            				param.start=(pageModel.curPage-1)*rPP;
            				if(param.start>totalRecords)
            					param.start=0;
            				param.limit=rPP;
            				param.length=rPP;
            			}
            		}
            		//设置排序参数
            		var setting = me.grid.pqGrid( "option", "dataModel" );
            		if(setting.sortIndx && setting.sortIndx.length>0){
            			param.sort = setting.sortIndx;
            			var columns = me.grid.pqGrid("option","colModel");
            			for(var i=0;i<columns.length;i++){
            				if(setting.sortIndx == columns[i].dataIndx){
            					if(columns[i].valueItem && columns[i].valueItem != ""){
            						param.sort = columns[i].valueItem;
            					}
            					break;
            				}
            			}
            			if(setting.sortDir == "up"){
            				param.sortdir = "asc";
            			}else if(setting.sortDir == "down"){
            				param.sortdir = "desc";
            			}
            		}
            		//判断是否分组，将其分组参数当做排序字段
            		if(config.groupdis && config.groupdis.length>0){
            			var groupdis = config.groupdis
            			var sort = "";
            			for(var i=0;i<groupdis.length;i++){
            				if(sort == ""){
            					sort = groupdis[i];
            				}else{
            					sort += ","+groupdis[i];
            				}
            			}
            			param.sort = sort+(param.sort!=null?(","+param.sort):"");
            		}
            	}
				me.loadingTags = IBiz.beginload();
                return { url: me.config.url, data: param };
            },
            getData:function( dataJSON, textStatus, jqXHR ){//获取返回参数
				IBiz.endload(me.loadingTags );
            	if(dataJSON.success){
            		me.tableselections = {};
            		me.changeRows = [];
            		me.selectRowIndx = [];
            		//呼出事件
            		setTimeout(function(){
            			me.fireEvent(IBizDataGrid.LOADED,me,dataJSON.items);
            		}, 1);
            		var startrow=dataJSON.startrow;
            		var limit = dataJSON.limit;
            		var curPage = startrow/limit+1;
					for(i=dataJSON.items.length-1;i>=0;i--){
	        			if(Object.prototype.toString.call(dataJSON.items[i]) == "[object Array]"){
	        				dataJSON.items.splice(i,1);
	        				continue;
	        			}
	        		}
					if(me.oldDataEdit){
						me.setRowNoEdit(dataJSON.items);
					}
					me.alldata = dataJSON.items;
					return { curPage: curPage, totalRecords: dataJSON.totalrow, data: dataJSON.items };
            	}else{
					IBiz.alert($IGM('IBIZDATAGRID.GETDATA.TITLE','加载错误信息'),$IGM('IBIZDATAGRID.GETDATA.INFO','加载数据发生错误,'+dataJSON.info,[dataJSON.info]),2);
					
				}
            	me.alldata = [];
				return {};
            }
		};
		//是否多选 ，默认为多选
		me.multiSelect = true; 
		if(config.multiSelect != undefined && config.multiSelect == false){
			me.multiSelect = config.multiSelect; 
		}
		//是否添加横向滚动条，默认添加
		me.forceFit=false; 
		if(config.forceFit != undefined && config.forceFit == true){
			me.forceFit = true;
		}
		//是否添加纵向滚动条，默认添加
		me.forceFitHeight=false;
		if(config.forceFitHeight != undefined && config.forceFitHeight == true){
			me.forceFitHeight = true;
		}
		//是否需要分割线
		me.freezeCols = true;
		if(config.freezeCols != undefined && config.freezeCols == false){
			me.freezeCols = config.freezeCols;
		}
		//是否分页，默认分页
		me.enablePaging = true; 
		var isShowBottom = true;
		if(config.enablePaging != undefined){
			me.enablePaging = config.enablePaging;
			isShowBottom = config.enablePaging;
		}
		//设置每页条数
		me.pageSize = 20; 
		if(config.pageSize && config.pageSize >0){
			me.pageSize = config.pageSize; 
		}
		//是否启用表格收缩功能
		me.collapsible = false;
		if(config.collapsible && config.collapsible == true){
			me.collapsible = {collapsed : true }; 
		}
		//是否显示顶部
		me.isShowTop = false;
		if(config.hideHeader != undefined && config.hideHeader == true){
			me.isShowTop = config.hideHeader; 
		}
		//是否启用编辑状态下老数据不可编辑
		me.oldDataEdit = false;
		if(config.oldDataEdit != undefined && config.oldDataEdit== true){
			me.oldDataEdit = config.oldDataEdit;
		}
		//是否可拖动表格
		me.isdragtable = false;
		if(config.isdragtable != undefined && config.isdragtable==true){
			me.isdragtable = config.isdragtable;
		}
		//是否启用行分组
		var groupCol = [];
		me.isGroupCol = false;
		if(config.groupdis){
			me.isGroupCol = true;
			groupCol = config.groupdis;
		}
		me.groupModel = {
			dataIndx: groupCol,
			collapsed: [ false, false],
			title: ["<b style='font-weight:bold;'>{0} ({1} "+$IGM('IBIZDATAGRID.CONSTRUCT.ROWGROUP','条')+")</b>",
					"<b style='font-weight:bold;'>{0} ({1} "+$IGM('IBIZDATAGRID.CONSTRUCT.ROWGROUP','条')+")</b>",
					"<b style='font-weight:bold;'>{0} ({1} "+$IGM('IBIZDATAGRID.CONSTRUCT.ROWGROUP','条')+")</b>",
					"<b style='font-weight:bold;'>{0} ({1} "+$IGM('IBIZDATAGRID.CONSTRUCT.ROWGROUP','条')+")</b>"],
			dir:['up','down']
		};
		
		//设置选中类型
//		me.selectionModel = { type: 'row', subtype:'incr', cbHeader:true, cbAll:true};
		me.selectionModel = {type: null};
		if(!me.multiSelect){
			me.selectionModel.type = "row";
			me.selectionModel.mode = "single";
		}
		//设置字段对应关系
		var colModel = [];
		var columns = me.config.columns;
		//判断是否启用行编辑
		me.isEditable=false;
		if(config.editable!=undefined && config.editable==true){
			me.editArr = [];
			me.isEditable=config.editable;			
		}
		//判断是否默认开启行编辑
		me.defaultEdit = false;
		if(config.defaultEdit!=undefined && config.defaultEdit==true && me.isEditable){
			me.defaultEdit = config.defaultEdit;
		}
		me.batchPaste = false;
		if(config.batchpaste != undefined && config.batchpaste == true){
			me.batchPaste = config.batchpaste;
		}
		me.colM = [];
		if(columns){
			if(me.multiSelect){
				var checkBox = { title: "", dataIndx: "checkbox_state", width: 30, minWidth:30, align: "center", type:'checkBoxSelection', cls: 'ibiz-pqgrid-checkbox', resizable: false, sortable:false, editable: false};
				colModel.push(checkBox);
			}
			for(var i=0;i<columns.length;i++){
				me.dealColums(columns[i],colModel);
			}
		}
		var toolbar = {};
		if(me.freezeCols){
			//锁定列功能
			toolbar.items =	[{type:"<span class='pq-toolbar-freeze' style='margin-left:20px;'>"+$IGM('IBIZDATAGRID.CONSTRUCT.LOCKLIFT','锁定前')+"</span>"},
		            	    { 
			            	cls: 'pq-toolbar-freeze',
		            		type: 'select', 
		                    listeners: [{ "change": function (evt, ui) {
		                    	var num = parseInt($(this).val());
		                        me.grid.pqGrid("option","freezeCols",num);
		                        me.grid.pqGrid("refresh");
		                    }
		                    }],
		                    options:[{"0":0},{"1": 1},{"2": 2},{"3": 3},{"4":4}]
		             	},{type:"<span class='pq-toolbar-freeze'>"+$IGM('IBIZDATAGRID.CONSTRUCT.LOCKRIGHT','列')+"</span>"}
		             	];
			//启用行编辑
//			toolbar.items.push({
//				type: 'button', 
//				label: '<i class="fa fa-pencil-square-o" aria-hidden="true"></i>&nbsp;启用', 
//				listeners: [{
//					"click": function(evt, ui){
//						var editFlag = me.getEditState();
//						if(editFlag){
//							me.grid.pqGrid("quitEditMode");
//							me.grid.pqGrid( "option", "selectionModel" ,me.selectionModel);
//							me.callbackData();
//						}else{
//							var dataM = me.grid.pqGrid("option","dataModel");
//				        	for(var i=0;i<dataM.data.length;i++){
//								dataM.data[i].checkBox = me.unSelectState;
//								me.grid.pqGrid("selection",{type:"row",method:"remove",rowIndx:i});
//							}
//				        	me.grid.pqGrid( "option", "selectionModel" ,{type: "cell"});
//						}
//						me.setEditState(!editFlag);
//					}
//				}]
//			});
			//提交数据
//			toolbar.items.push({
//				type: 'button', 
//				label: '<i class="fa fa-check" aria-hidden="true"></i>&nbsp;提交', 
//				listeners: [{
//					"click": function(evt, ui){
//						if(me.getEditState()){
//							me.quitEdit();
//						}
//					}
//				}]
//			});
		}
		if(me.grid){
			me.grid = me.grid.pqGrid({
				editable: me.defaultEdit,
				selectionModel: me.selectionModel,
				draggable: me.isdragtable,
				wrap: false,
				stripeRows: true,
				rowBorders: true,
				showHeader: true, 
				checkbox: true,
				collapsible: me.collapsible,
				width: me.getWidth(),
				height: me.getHeight(),
				showTop: me.isShowTop,
				showTitle: false,
				showToolbar: me.isShowTop,
				columnBorders: false,
				showBottom: isShowBottom,
				numberCell: { show: false },
				scrollModel: { autoFit: false ,lastColumn:'auto'},
				flexWidth: me.forceFit,
				flexHeight: me.forceFitHeight,
				pageModel: me.getPagingModel(),
				dataModel: dataModel,
				colModel: colModel,
				groupModel: me.groupModel,
				swipeModel: {on: false}, //拖拽滑动
				track:true,
				freezeCols: 0,
				virtualX: false, 
				virtualY: false,
				toolbar: toolbar,
				editModel:{
					saveKey: $.ui.keyCode.ENTER,
				    cellBorderWidth: 0 //表示编辑边框线宽度
				},
				editor: { type: "textbox",style:"width:100%;"},				 			 		
				
	            create: function(ui){
	            	var $grid = $(this);
	                var $toolbar = $grid.find(".pq-toolbar").find(".pq-toolbar-freeze");
	            	var $paper = $grid.find(".pq-grid-bottom ").find(".pq-pager");
	            	
	            	if($toolbar && $paper){
	            		$toolbar = $toolbar.detach();
	            		$paper.append($toolbar);
	            	}
	            },
	            load: function(event, ui){
					if(me.getEditState()) {
						me.grid.pqGrid( "option", "showBottom", false );
						me.grid.pqGrid("option","pageModel.rPP",1000);
					}
	            	me.fireEvent(IBizDataGrid.CHANGEEDITSTATE,me,{state:me.getEditState()});
	            	me.fireEvent(IBizDataGrid4.PQGRIDCHANGEGROUPM,me,me.grid.pqGrid("option","groupModel.dataIndx"));
	            },
				rowSelect: function(event,ui){ //单击选中事件抛出
					if(me.getEditState()){
						me.grid.pqGrid("quitEditMode");
					}
					
					if(ui.rows){
						$.each(ui.rows, function(i, row){
							me.onRowSelect(row);
						});
					} else {
						me.onRowSelect(ui);
					}
				},
				rowUnSelect: function(event,ui){ //取消选中事件
					if(me.getEditState()) {
						return;
					}
					me.setSelection();
				},
				rowDblClick: function(event,ui){ //双击事件抛出
					if(me.getEditState() || !ui.rowData.srfkey){
						return;
					}
					me.fireEvent(IBizDataGrid.ROWDBLCLICK,event,ui.rowData);
				},
				cellSelect: function(event,ui){
					me.grid.pqGrid("quitEditMode");
				},
				editorEnd: function(event, ui) {
			        if (event.keyCode != $.ui.keyCode.ESCAPE && event.keyCode != $.ui.keyCode.TAB) {
			        	me.grid.pqGrid("saveEditCell");
			        }
				},
				beforeValidate: function( event, ui ) {
					if(ui.source === "paste" && ui.rowList) {
						me.pasteData(ui.rowList);
						return false;
					}
				},
				cellClick: function( event, ui ) {
					if(ui.dataIndx == "checkbox_state" && me.getEditState()) {
						if(ui.rowData.checkbox_state) {
							if(me.selectRowIndx.indexOf(ui.rowIndx) < 0){
								me.selectRowIndx.push(ui.rowIndx);
							}
						} else {
							for(var i=me.selectRowIndx.length-1;i>=0;i--){
								if(me.selectRowIndx[i] == ui.rowIndx){
									me.selectRowIndx.splice(i,1);
								}
							}
						}
						if(me.selectRowIndx.length > 0) {
							$.each(me.selectRowIndx, function(indx, rowIndx){
								me.grid.pqGrid("selection",{type: "row",method: "add",rowIndx: rowIndx});
							})
						} else {
							me.setSelection();
						}
					}
				}
			});
		}	
		//设置中文
		me.grid.pqGrid("option", $.paramquery.pqGrid.regional[locale]);            
		me.grid.find(".pq-pager").pqPager("option", $.paramquery.pqPager.regional[locale]);       
		me.grid.pqGrid("refresh");
		
		me.grid.on("change",".pq-grid-header .ibiz-pqgrid-checkbox input",function(event){
			if(!this.checked){
				me.selectRowIndx = [];
			}
		});
		//表格行编辑保存		
		me.grid.on("pqgridcellsave", function (event, ui) {
			me.fireEvent(IBizDataGrid.UPDATEGRIDITEMCHANGE,me,ui);
		});
		//行编辑回填数据前处理
		me.grid.on("pqgridcellbeforesave",function(event,ui){
			var changeRow = {};
			var flag = true;			
			//将改变的行放入me.changeRows数组中
			if (ui.newVal != ui.oldVal) {
				ui.rowData[ui.dataIndx] = ui.newVal;
				//判断是否已经更改过，替换内容
				me.setRowEditChangeData({rowData: ui.rowData,rowIndx: ui.rowIndx,dataIndx: ui.dataIndx});
				//给该单元格添加标记
				me.grid.pqGrid("addClass",{rowIndx:ui.rowIndx,dataIndx:ui.dataIndx,cls:"pq-cell-dirty"});								
			}
		});
		
		var isVisible = me.grid.is(":visible");
		if(!isVisible){
			var inter = setInterval(function(){
				isVisible = me.grid.is(":visible");
				if(isVisible){ 
					if(me.lastVisible)
						return;
					me.setSize( me.grid.parent().width(),me.grid.height()+2);
					me.lastVisible = true;
				}else{
					me.lastVisible = false;
				}
			},200);
			window.onresize = function(){
				if(isVisible){
					me.setSize( me.grid.parent().width(),me.grid.height()+2);
					me.grid.pqGrid("refresh");
				}
			}
		}
		if(me.getController() && !me.getController().isAutoLayout()) {
			$(window).resize(function(){
				me.grid.pqGrid( "refresh" );
			});
		}
	},
	//递归处理表格列
	dealColums: function(col,colModel){
		var me = this;
		var column = {};
		//判断是否有列分组情况
		if(col.columns){
			var cols = []
			column.title = col.title;
			column.align = "center";
			for(var i=0;i<col.columns.length;i++){
				me.dealColums(col.columns[i],cols);
			}
			column.colModel = cols;
		}else{
			me.colM.push(col.title);
			column = {title: col.title,align: col.sClass,dataType: col.dataType,headTitle: col.title,width: col.width,hidden:col.hidden,dataIndx: col.data};
			if(col.valueItem){
				column.valueItem = col.valueItem;
			}
			column.sortable = col.orderable;
			if(col.render){
				column.render2 = col.render;
				column.render = function(ui){
					return ui.column.render2(ui.cellData,'',ui.rowData);
				}
			}
			//判断表单可编辑时对数据进行回写
			if(me.isEditable){
				if(col.editor){
					me.editArr.push(col.data);
					column.editable = true;
					column.editor = col.editor;
					column.title = col.title;
				}else{
					column.editable = false;
				}
			}
		}
		colModel.push(column);
	},
	onRowSelect: function(ui){
		var me = this;
		var datas = me.grid.pqGrid("option", "dataModel").data;
		var index = ui.rowIndx;
		if(me.enablePaging) {
			var pageM = me.grid.pqGrid("option", "pageModel");
			index = index - (pageM.rPP * (pageM.curPage - 1));
		}
		if(datas[index].hasOwnProperty("checkbox_state")) {
			datas[index].checkbox_state = true;
			me.grid.pqGrid( "refreshCell", { rowIndx: ui.rowIndx, dataIndx: 'checkbox_state' } );
		}
		if(me.selectRowIndx.indexOf(ui.rowIndx) < 0){
			me.selectRowIndx.push(ui.rowIndx);
		}
		me.setSelection();
	},
	/**
	 * 粘贴数据
	 */
	pasteData: function(datas) {
		var me = this;
		if(me.isGroupCol) {
			return;
		}
		var pasteDatas = [];
		if(me.getEditState() && datas && datas.length > 0) {
			var columns = [];
			var colModel = me.grid.pqGrid("option", "colModel");
			$.each(colModel, function(i, col){
				columns.push(col.dataIndx);
				if(datas[0].newRow.hasOwnProperty(col.dataIndx) && col.valueItem) {
					$.each(datas, function(index, data){
						data.newRow[col.valueItem] = data.newRow[col.dataIndx];
					});
				}
			});
			$.each(datas, function(index, data){
				var param = {};
				$.extend(param, data.newRow);
				param.srfaction = "loaddraftpaste";
				IBiz.ajax({
					url: me.config.url,
					params: param,
					method: 'POST',
					async: false,
					dataType: 'json',
					success: function(result) {
						if(result.ret == 0) {
							if(me.batchPaste && data.type == "update"){
								index = data.rowIndx;
								$.each(result.data, function(key, value){
									if(value != "" && columns.indexOf(key) >= 0) {
										data.rowData[key] = value;
										me.setRowEditChangeData({rowData: data.rowData,rowIndx: index,dataIndx: key});
										me.grid.pqGrid("refreshCell", {rowIndx:index, dataIndx:key});
										me.grid.pqGrid("addClass", {rowIndx:index, dataIndx:key, cls:"pq-cell-dirty"});
									}
								});
							} else {
								index = me.createNewRow(result.data, "paste");
								$.each(result.data, function(key, value){
									if(value != "") {
										me.grid.pqGrid("addClass", {rowIndx:index, dataIndx:key, cls:"pq-cell-dirty"});
									}
								});
							}
						} else {
							IBiz.alert("粘贴失败！");
						}
					},
					error: function(e) {
						IBiz.alert("粘贴失败！");
					}
				});
			});
		}
	},
	//设置行编辑改变数据
	setRowEditChangeData: function(row){
		var me = this;
		var flag = true;
		var changeRow = {};
		
		for(var i=0;i<me.changeRows.length;i++){
			if(me.changeRows[i].index == row.rowIndx){
				me.changeRows[i].rowData = row.rowData;
				if(me.changeRows[i].dataIndexs){
					if(me.changeRows[i].dataIndexs.indexOf(row.dataIndx)<0)
						me.changeRows[i].dataIndexs.push(row.dataIndx);
				}else{
					me.changeRows[i].dataIndexs = [];
					me.changeRows[i].dataIndexs.push(row.dataIndx);
				}
				flag = false;
				break;
			}
		}
		if(flag){
			changeRow.index = row.rowIndx;
			changeRow.rowData = row.rowData;
			changeRow.dataIndexs = [];
			changeRow.dataIndexs.push(row.dataIndx);
			me.changeRows.push(changeRow);
		}
	},
	//是否启用行编辑
	isOpenEdit: function(params){
		var me = this;
		if(!me.isEditable){
			IBiz.alert($IGM('IBIZDATAGRID.ISOPENEDIT.INFO','表格未开启行编辑功能！'));
			return;
		}
		me.$buttonTag = params;
		var editFlag = me.getEditState();
		if(editFlag){
			me.grid.pqGrid("quitEditMode");
			if(me.changeRows.length>0){
				if(confirm($IGM('IBIZDATAGRID.ISOPENEDIT.CONFIRM',"有部分数据已修改，是否关闭行编辑？"))){
					me.callbackData();
				}else{
					return;
				}
			}
			me.grid.pqGrid( "option", "selectionModel",  me.selectionModel);
			me.grid.pqGrid("option","pageModel.rPP",me.rPP);
			me.grid.pqGrid( "option", "sortable", true );
			me.$buttonTag.state = false;
			var selectCell = me.grid.pqGrid( "selection",{ type: 'cell', method: 'getSelection' });
			$.each(selectCell, function(i, cell){
				me.grid.pqGrid( "selection", { type: 'cell', method: 'remove', rowIndx: cell.rowIndx, colIndx: cell.colIndx});
			});
			me.refresh();
		}else{
			var dataM = me.grid.pqGrid("option","dataModel");
        	for(var i=0;i<dataM.data.length;i++){
        		if(me.multiSelect){
        			dataM.data[i].checkbox_state = false;
        			me.grid.pqGrid( "refreshCell", { rowIndx: i, dataIndx: 'checkbox_state' } );
        		}
				me.grid.pqGrid("selection",{type:"row",method:"remove",rowIndx:i});
			}
        	me.$buttonTag.state = true;
        	me.grid.pqGrid( "option", "selectionModel",  { type: 'cell', mode: 'block'});
        	me.rPP = me.grid.pqGrid( "option", "pageModel.rPP" );
        	me.grid.pqGrid("option","pageModel.rPP",1000);
        	me.grid.pqGrid( "option", "sortable", false );
        	me.selectRowIndx = [];
        	me.setSelection();
		}
		me.setEditState(!editFlag);
		me.fireEvent(IBizDataGrid.CHANGEEDITSTATE,me,params);
		
	},
	//获取新建行数据
	newRowAjax: function(arg){
		var me = this;
		if(!me.getEditState()){
			return;
		}
		me.grid.pqGrid("quitEditMode");
		if(me.isGroupCol){
			IBiz.alert($IGM('IBIZDATAGRID.NEWROWAJAX.INFO2','启用分组时不可新建行数据!'));
			return;
		}
		var param = {srfaction:'loaddraft'};
		$.extend(param, arg);
		
		IBiz.ajax({
			url: me.config.url,
			params: param,
			method: 'POST',
			dataType: 'json',
			success: function(data) {
				if(data.success){
					data.data.newCreateRow = true;
					me.createNewRow(data.data);
				}else{
					IBiz.alert($IGM('IBIZAPP.CONFIRM.TITLE.ERROR','错误'),$IGM('IBIZDATAGRID.NEWROWAJAX.INFO','获取默认数据失败,'+data.error,[data.error]),2);
					
				}
			},
			failure: function(e) {
				IBiz.alert($IGM('IBIZAPP.CONFIRM.TITLE.INFO','信息'));											
			}
		});
	},
	//获取表格编辑状态
	getEditState: function(){
		var me = this;
		return me.grid.pqGrid( "option", "editable" );
	},
	setEditState: function(flag){
		var me = this;
		me.grid.pqGrid( "option", "showBottom", !flag );
		me.grid.pqGrid( "option", "editable", flag);
	},
	//撤销数据
	callbackData: function(){
		var me = this;
		me.grid.pqGrid("refreshDataAndView");
		me.changeRows = [];
		console.log(me.changeRows);
	},
	//设置该数据不可编辑
	setRowNoEdit: function(data){
		var me = this;
		for(var i=0;i<data.length;i++){
			data[i].editCellFlag = true;
		}
	},
	//在表格中创建新行
	createNewRow: function(data, type){
		var me = this;
		var rowData = {};
		$.extend(rowData,data);
		var rowIndx = me.grid.pqGrid("addRow", { rowData: rowData });
		var newRow = {};
		newRow.index = rowIndx;
		newRow.rowData = rowData;
		newRow.dataIndexs = [];
		$.each(data, function(key, val){
			if(val){
				newRow.dataIndexs.push(key);
			}
		});
		me.changeRows.push(newRow);
		if(type === "paste"){
			me.grid.pqGrid("refreshRow", { rowIndx: rowIndx });
		}else {
			me.grid.pqGrid("editFirstCellInRow", { rowIndx: rowIndx });
		}
        return rowIndx;
	},
	//删除本地选中数据
	removeLocalData: function(){
		var me = this;
		var selects = me.grid.pqGrid('selection', { type: 'row', method: 'getSelection' });
		for(var i=selects.length-1;i>=0;i--){
			if(!selects[i].rowData.srfkey){
				me.grid.pqGrid("deleteRow",{rowIndx:selects[i].rowIndx});
				me.selectRowIndx.splice(me.selectRowIndx.indexOf(selects[i].rowIndx),1);
			}
		}
	},
	//提交编辑
	quitEdit: function(){
		var me = this;
		var num = 0;
		var errorIndex = [];
		me.grid.pqGrid("quitEditMode");
		me.saveEditBefore(num,errorIndex);	
	},
	//插入行数据
	insertRow: function(num,errorIndex){
		var me = this;
		var rowData=me.changeRows[num].rowData;
		var arg = rowData;
		arg.srfaction = "create";
		me.saveEdit(arg,num,errorIndex,"edit");
	},
	//发送请求保存数据
	saveEditBefore:function(num,errorIndex){
		var me=this;
		if(num<me.changeRows.length){
			var rowData=me.changeRows[num].rowData;
			
			//该行为新建行
			if(!rowData.srfkey){
				me.insertRow(num,errorIndex);
				return;
			}
			
			var arg={};
			$.extend(arg,rowData);
							
			arg.srfkey=rowData.srfkey;
			arg.srfaction = 'update';			
			me.saveEdit(arg,num,errorIndex,"edit");						
		}else{
			var errorInfo="";
			for(var k=0;k<errorIndex.length;k++){
				errorInfo+=$IGM('IBIZDATAGRID.SAVEEDITBEFORE.INFO2',"第"+(errorIndex[k].rowIndex+1)+"行修改失败，错误原因：",[(errorIndex[k].rowIndex+1)])+'<br/>';
				var items = errorIndex[k].errorItems;
				for(var i=0;i<items.length;i++){
					errorInfo += items[i].info+'<br/>';
				}
			}
			if(errorIndex.length>0){
				IBiz.alert($IGM('IBIZAPP.CONFIRM.TITLE.ERROR','错误'),$IGM('IBIZDATAGRID.SAVEEDITBEFORE.INFO','提交数据失败,'+errorInfo,[errorInfo]),2);
			}else {
				me.changeRows = [];
			}
		}	
	},
	//处理编辑数据保存返回数据
	editResponse: function(data, num, arr){
		var me = this;
		var index = me.changeRows[num].index;
		var dataIndxs = me.changeRows[num].dataIndexs;
		
		if (data.success) {
			$.extend(me.changeRows[num].rowData,data.data);
			me.changeRows[num].rowData.newCreateRow = false;
			if(me.oldDataEdit){
				me.changeRows[num].rowData.editCellFlag = true;
			}
			me.grid.pqGrid("refreshRow",{rowIndx:me.changeRows[num].index});
			for(var m=0;m<dataIndxs.length;m++){	
				var dataIndx = dataIndxs[m];
				me.grid.pqGrid( "removeClass", {rowIndx: index, dataIndx:dataIndx, cls: "pq-cell-dirty"});
			}
		} else {
			var error = {};
			error.rowIndex = index;
			if(data.error){
				error.errorItems = data.error.items;
			}else{
				error.errorItems = [{info:data.info}];
			}
			arr.push(error);
		}
		num++;
		me.saveEditBefore(num,arr);
	},
	//行编辑请求
	saveEdit: function(arg,num,arr,type){
		var me = this;
		IBiz.ajax({
			url: me.config.url,
			params: arg,
			method: 'POST',
			dataType: 'json',
			success: function(data) {
				if(type === "edit") {
					me.editResponse(data, num , arr);
				}
			},
			failure: function(e) {
				IBiz.alert($IGM('IBIZAPP.CONFIRM.TITLE.INFO','信息'));											
			}
		});
	},
	//设置选中值
	setSelection : function(){
		var me = this;
		var data = [];
		me.tableselections = {};
		me.tableselection = null;
        var selects = me.grid.pqGrid('selection', { type: 'row', method: 'getSelection' });
		for (var i = 0, len = selects.length; i < len; i++) {
            var rowData = selects[i].rowData;
            data.push(rowData);
            me.tableselections[rowData.srfkey] = rowData;
			me.tableselection = rowData;
        }
		me.fireEvent(IBizDataGrid.SELECTIONCHANGE,me,data);
	},
	//获取pageModel值
	getPagingModel : function(){
		var me = this;
		if(me.enablePaging){
			var pageMode = {type: "remote",rPP: me.pageSize,strRpp: "{0}"};
			return pageMode;
		}
		return false;
	},
	reSetHeight: function(height){
		var me = this;
		var gridHeight = me.grid.pqGrid( "option", "height");
		if(gridHeight-height<0){
			height = 0
		}else{
			height = gridHeight-height;
		}
		me.grid.pqGrid( "option", "height", height);
	},
	//设置表格大小随窗口大小改变
	setSize : function(width,height){
		var me = this;
		me.layoutHeight = height;
		me.layoutWidth = width;
		if(me.grid){
			me.grid.pqGrid( "option", "width", width-3);
			me.grid.pqGrid( "option", "height", height-2);
			me.grid.pqGrid( "refresh" );
		}
	},
	//设置表格宽度
	getWidth : function(){
		var me = this;
		if(me.config.width && me.config.width >0){
			return me.config.width;
		}
		return "100%";
	},
	//设置表格高度
	getHeight : function(){
		var me = this;
		if(me.layoutHeight && me.layoutHeight > 0){
			return me.layoutHeight;
		}
		if(me.config.height && me.config.height >0){
			return me.config.height;
		}
		if(me.grid.parent().height() >0){
			return me.grid.parent().height()-2;
		}
		if(me.grid.height() >0){
			return me.grid.height();
		}
		return;
	},
	//获取选中数据
	getSelection:function(){
		var me = this;
		if(me.tableselections){
			var data = [];
			$.each(me.tableselections,function(key,value){
				data.push(value);
			});
			
			return data;
		}
		return [];
	},
	getAllData:function(){
		var me = this;
		return me.alldata;
	},
	//删除
	remove: function(arg) {
		var me = this;
		if (!arg.srfkeys){
			me.removeLocalData();
			return;
		}
		if (!arg) arg = {};
		$.extend(arg, {
			srfaction: 'remove'
		});
		if (IBizApp_Data) {
			arg.srfappdata = IBizApp_Data;
		}
		me.loadingTag = IBiz.beginload();
		IBiz.ajax({
			url: me.config.url,
			params: arg,
			method: 'POST',
			dataType: 'json',
			success: function(data) {
				IBiz.endload(me.loadingTag );
				if (data.ret == 0) {
					me.tableselection = null;
					me.tableselections = {};
					me.refresh();
					me.fireEvent(IBizDataGrid.REMOVED,me,data);
					if (data.info && data.info != '') {
						IBiz.alert($IGM('IBIZDATAGRID.REMOVE.INFO','删除成功'), data.info);
					}
					IBiz.processResult(data);
				} else {
					IBiz.alert($IGM('IBIZDATAGRID.REMOVE.TITLE','删除失败'),$IGM('IBIZDATAGRID.REMOVE.INFO2','删除数据失败,'+ data.info,[data.info]),2);
				}
			},
			failure: function(e) {
				IBiz.endload(me.loadingTag );
				IBiz.alert($IGM('IBIZAPP.CONFIRM.TITLE.INFO','信息'));
			}
		});
	},
	//重新加载，调用刷新功能
	load:function(){
		var me = this;
		me.grid.pqGrid( "option", "pageModel.curPage", 1);
		me.grid.pqGrid( "refreshDataAndView" );
	},
	//刷新
	refresh:function(){
		var me = this;
		me.grid.pqGrid( "refreshDataAndView" );
	},
	//获取数据仓库<该方法仅在Ext版本中有效>
	getStore:function(){
		return null;
	},
	/**
	 * 表格项更新
	 */
	updateGridEditItems: function(param,args){
		var me = this;
		if(!param)
			return;
		me.updateState = true;
		param["srfaction"] = "updategridedititem";
		param["srfactivedata"] = JSON.stringify(args.rowData);
		IBiz.ajax({url:me.config.url,
			params: param,
			method: 'POST',
			dataType: 'json',
			success: function(data){
				if(data.ret == 0){
					var rowData = args.rowData;
					var rowIndx = args.rowIndx;
					var changeDatas = [];
					$.each(me.changeRows,function(index,row){
						if(rowIndx == row.index) {
							changeDatas = row.dataIndexs;
						}
					});
					$.each(data.data,function(key,val){
						var val1 = (rowData[key] && rowData[key] != 0)? rowData[key]: '';
						var val2 = (val && val != 0)? val: '';
						if (val1 != val2) {
							if(changeDatas.indexOf(key) < 0) {
								changeDatas.push(key);
							}
							rowData[key] = val;
							me.grid.pqGrid( "refreshCell", { rowIndx: rowIndx, dataIndx: key } );
							me.grid.pqGrid("addClass",{rowIndx:rowIndx,dataIndx:key,cls:"pq-cell-dirty"});
						}
					});
					me.updateState = false;
				}
			},
			failure: function(e){
				IBiz.alert($IGM('IBIZAPP.CONFIRM.TITLE.INFO','表格项更新失败！'));
			}
		});
	},
	doUIAction: function(params) {
		var me = this;
		var callback;
		if(params || params.callback){
			callback = params.callback;
			delete params.callback;
		}
		if (!params) params = {};
		$.extend(params,{srfaction: 'uiaction'});
		if (IBizApp_Data) {
			params.srfappdata = IBizApp_Data;
		}
		me.loadingTag = IBiz.beginload();
		IBiz.ajax({url:me.config.url,
			params:params,
			method:'POST',
			dataType:'json',
			success:function(data){
				IBiz.endload(me.loadingTag );
				if(data.ret == 0){
					if(data.reloadData){
						me.refresh();
					}
					if (data.info && data.info != '') {
						IBiz.alert($IGM('IBIZDATAGRID.DOUIACTION.INFO','操作成功'), data.info);
					}
					IBiz.processResult(data);
					
					if(callback && typeof(callback) == 'function'){
						callback({success:true,data:data});
					}
				}else{
					IBiz.alert($IGM('IBIZDATAGRID.DOUIACTION.TITLE','操作失败'),$IGM('IBIZDATAGRID.DOUIACTION.INFO2','操作失败,执行操作发生错误,'+ data.info,[data.info]),2);
					if(callback && typeof(callback) == 'function'){
						callback({success:false,data:data});
					}
				}
			},
			failure:function(e){
				IBiz.endload(me.loadingTag );
				IBiz.alert($IGM('IBIZAPP.CONFIRM.TITLE.INFO','信息'));
				if(callback && typeof(callback) == 'function'){
					callback({success:false,e:e});
				}
			}	
		});
	},
	//提交工作流操作
	wfsubmit: function(params) {
		var me = this;
		if (!params) params = {};
		$.extend(params, {
			srfaction: 'wfsubmit'
		});
		if (IBizApp_Data) {
			params.srfappdata = IBizApp_Data;
		}
		me.loadingTag = IBiz.beginload();
		IBiz.ajax({
			url: me.config.url,
			params: params,
			method: 'POST',
			dataType: 'json',
			success: function(data) {
				IBiz.endload(me.loadingTag );
				if (data.ret == 0) {
					me.refresh();
				} else {
					IBiz.alert($IGM('IBIZDATAGRID.WFSUBMIT.TITLE','执行失败'),$IGM('IBIZDATAGRID.WFSUBMIT.INFO','执行工作流操作失败,'+ data.info,[data.info]),2);
				}
			},
			failure: function(e) {
				IBiz.endload(me.loadingTag );
				IBiz.alert($IGM('IBIZAPP.CONFIRM.TITLE.INFO','信息'));
			}
		});
	},
	//批量添加
	addBatch: function(arg) {
		var me = this;
		if (!arg) arg = {};
		$.extend(arg, {srfaction: 'addbatch'});
		
		if (IBizApp_Data) {
			arg.srfappdata = IBizApp_Data;
		}
		me.loadingTag = IBiz.beginload();
		IBiz.ajax({
			url: me.config.url,
			params: arg,
			method: 'POST',
			dataType: 'json',
			success: function(data) {
				IBiz.endload(me.loadingTag );
				if (data.ret == 0) {
					me.refresh();
					me.fireEvent(IBizDataGrid.ADDBATCHED,me,data);
				} else {
					IBiz.alert($IGM('IBIZDATAGRID.ADDBATCH.TITLE','添加失败'),$IGM('IBIZDATAGRID.ADDBATCH.INFO','执行批量添加失败,'+ data.info,[data.info]),2);
				}
			},
			failure: function(e) {
				IBiz.endload(me.loadingTag );
				IBiz.alert($IGM('IBIZAPP.CONFIRM.TITLE.INFO','信息'));
			}
		});
	},
	//导出数据
	exportData: function(arg) {
		var me = this;
		
		var params={};
		me.fireEvent(IBizDataGrid.BEFORELOAD,me,params);
		params['query'] = params['search'];
		params['srfaction']='exportdata';
		
		var setting = me.grid.pqGrid( "option", "dataModel" ); 
		if(setting.sortIndx && setting.sortIndx.length>0){
			params['sort'] = setting.sortIndx;
			if(setting.sortDir == "up"){
				params["sortdir"] = "asc";
			}else if(setting.sortDir == "down"){
				params["sortdir"] = "desc";
			}
		}
		
		var pageModel = me.grid.pqGrid("option","pageModel");
		if(arg.itemtag == 'all'){
			params['start'] = 0;
			params['limit'] = arg.exportlimit?arg.exportlimit:1000;
		}else if(arg.itemtag == 'custom'){
			var nStart = parseInt(arg.obj.find('.ibiz-id-start').val());
			var nEnd = parseInt(arg.obj.find('.ibiz-id-end').val());
			if(isNaN(nStart) || isNaN(nEnd) || (nStart<1 || nEnd <1 || nStart >nEnd)){
				IBiz.alert($IGM('IBIZAPP.CONFIRM.TITLE.WARN','警告'),$IGM('IBIZDATAGRID.EXPORTDATA.INFO','请输入有效的起始页'),0);
				return;
			}
			params['start'] = (nStart-1)*pageModel.rPP;
			params['limit'] = (nEnd-nStart+1)*pageModel.rPP;
		}else{
			params['start'] = (pageModel.curPage-1)*pageModel.rPP;
			params['limit'] = pageModel.rPP;
		}
		
		if(params['limit'] >65534){
			IBiz.alert($IGM('IBIZAPP.CONFIRM.TITLE.WARN','警告'),$IGM('IBIZDATAGRID.EXPORTDATA.INFO3','超出导出范围'),0);
			return;
		}
		
		if (IBizApp_Data) {
			params.srfappdata = IBizApp_Data;
		}
		me.loadingTag = IBiz.beginload();
		IBiz.ajax({
			url: me.config.url,
			params: params,
			method: 'POST',
			dataType: 'json',
			success: function(data) {
				IBiz.endload(me.loadingTag );
				if (data.ret == 0) {
					if(data.downloadurl){
						var downloadurl = BASEURL+ data.downloadurl;
						IBiz.download(downloadurl);
					}
				} else {
					IBiz.alert($IGM('IBIZDATAGRID.EXPORTDATA.TITLE','导出失败'),$IGM('IBIZDATAGRID.EXPORTDATA.INFO2','导出数据失败,' + data.info,[data.info]),2);
				}
			},
			failure: function(e) {
				IBiz.endload(me.loadingTag );
				IBiz.alert($IGM('IBIZAPP.CONFIRM.TITLE.INFO','信息'));
			}
		});
	}
		
});
/*****************事件声明************************/
//表格行分组改变
IBizDataGrid4.PQGRIDCHANGEGROUPM = "PQGRIDCHANGEGROUPM";
